package com.xmindguoguo.boot.modular.system.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.xmindguoguo.boot.common.annotation.OperationLog;
import com.xmindguoguo.boot.common.constant.GlobalConstant;
import com.xmindguoguo.boot.common.enumtype.OperationLogType;
import com.xmindguoguo.boot.core.BaseController;
import com.xmindguoguo.boot.core.shiro.ShiroKit;
import com.xmindguoguo.boot.modular.system.model.TSystemRoleModel;
import com.xmindguoguo.boot.modular.system.model.TSystemUserModel;
import com.xmindguoguo.boot.modular.system.service.ITSystemRoleService;
import com.xmindguoguo.boot.modular.system.service.ITSystemUserService;
import com.xmindguoguo.boot.util.CmUtil;
import com.xmindguoguo.boot.util.ConvertUtil;
import com.xmindguoguo.boot.util.ToolUtil;
import com.xmindguoguo.boot.util.json.JsonResult;

/**
 * <p>
 * 管理员表 前端控制器
 * </p>
 *
 * @author xmind-guoguo
 * @since 2018-11-04
 */
@Controller
@RequestMapping("/systemUser")
public class SystemUserController extends BaseController {
    @Autowired
    public ITSystemUserService systemUserService;
    @Autowired
    private ITSystemRoleService systemRoleService;

    @RequestMapping("toSystemUserList")
    public String toSystemUserList() {
        return "system/systemUser/systemUserList"; // 跳转到列表页
    }

    // 查询列表数据 加上分页
    @RequestMapping("systemUserList")
    @ResponseBody
    public Object systemUserList(TSystemUserModel model, @RequestParam(value = "page", required = false) Integer current,
            @RequestParam(value = "limit", required = false) Integer size) {
        Wrapper<TSystemUserModel> wrapper = new EntityWrapper<>();
        if (ToolUtil.isNotEmpty(model.getAccount())) {
            wrapper.like("account", model.getAccount());
        }
        if (ToolUtil.isNotEmpty(model.getPhone())) {
            wrapper.like("phone", model.getPhone());
        }
        wrapper.ne("status", GlobalConstant.MODEL_DEL);
        wrapper.orderBy("createTime", false);
        Page<TSystemUserModel> page = new Page<>(current, size);
        return JsonResult.sendPage(systemUserService.selectPage(page, wrapper)); // 跳转到列表页
    }

    @RequestMapping("toSystemUserAdd")
    public String toSystemUserAdd() {
        setRoleList();
        return "system/systemUser/systemUserAdd"; // 跳转到列表页
    }

    /**
     * 设置角色list
     * 
     * @Title setRoleList
     * @author 于国帅
     * @date 2019年1月1日 下午2:55:11 void
     */
    private void setRoleList() {
        Wrapper<TSystemRoleModel> wrapper = new EntityWrapper<>();
        wrapper.ne("status", GlobalConstant.MODEL_DEL);
        wrapper.orderBy("createTime", false);
        List<TSystemRoleModel> roleList = systemRoleService.selectList(wrapper);
        request.setAttribute("roleList", roleList);
    }

    @OperationLog(logName = "添加用户", operationLogType = OperationLogType.INSERT)
    @RequestMapping("systemUserAdd")
    @ResponseBody
    public Object systemUserAdd(@Validated TSystemUserModel mode, BindingResult result) {
        if (result.hasErrors()) {
            return sendValidatedMsg(result);
        }
        // 查询登录账号是否重复
        if (systemUserService.getByAccount(mode.getAccount()) != null) {
            return JsonResult.sendError("添加失败,账号存在重复", null);
        }
        mode.setId(CmUtil.getPkId());
        mode.setStatus(GlobalConstant.MODEL_ADD);
        mode.setSalt(RandomStringUtils.random(6, true, true));
        mode.setPassword(ShiroKit.md5(mode.getPassword(), mode.getSalt()));
        mode.setCreateTime(new Date());
        boolean flag = systemUserService.insert(mode);
        return flag ? JsonResult.sendOk("添加成功", null) : JsonResult.sendError("添加失败", null);
    }

    @RequestMapping("toSystemUserUpdate")
    public String toSystemUserUpdate(Long id) {
        TSystemUserModel model = systemUserService.selectById(id);
        request.setAttribute("model", model);
        setRoleList();
        return "system/systemUser/systemUserUpdate"; // 跳转到列表页
    }

    @OperationLog(logName = "更新用户", operationLogType = OperationLogType.UPDATE)
    @RequestMapping("systemUserUpdate")
    @ResponseBody
    public Object systemUserUpdate(@Validated TSystemUserModel model, BindingResult result) {
        if (result.hasErrors()) {
            return sendValidatedMsg(result);
        }
        if (StringUtils.isNotEmpty(model.getOldPassword())) { // 更新面膜
            TSystemUserModel oldModel = systemUserService.selectById(model.getId());
            model.setOldPassword(ShiroKit.md5(model.getOldPassword(), oldModel.getSalt()));
            if (!oldModel.getPassword().equals(model.getOldPassword())) {
                return JsonResult.sendError("更新失败,旧密码不一致", null);
            }
            model.setPassword(ShiroKit.md5(model.getPassword(), oldModel.getSalt()));
        }
        model.setUpdateTime(new Date());
        boolean flag = systemUserService.updateById(model);
        return flag ? JsonResult.sendOk("更新成功", null) : JsonResult.sendError("更新失败", null);
    }

    @OperationLog(logName = "删除用户", operationLogType = OperationLogType.DELETE)

    @RequestMapping("systemUserDelete")
    @ResponseBody
    public Object systemUserDelete(Long id) {
        TSystemUserModel model = new TSystemUserModel();
        model.setStatus(GlobalConstant.MODEL_DEL);
        model.setId(id);
        boolean flag = systemUserService.updateById(model);
        return flag ? JsonResult.sendOk("删除成功", null) : JsonResult.sendError("删除失败", null);
    }

    @OperationLog(logName = "批量删除用户", operationLogType = OperationLogType.DELETE)
    @RequestMapping("systemUserBatchDel")
    @ResponseBody
    public Object systemUserBatchDel(String ids) {
        Long[] idsArray = ConvertUtil.StringToLongArray(ids);
        List<TSystemUserModel> list = new ArrayList<>();
        TSystemUserModel model = null;
        for (Long id : idsArray) {
            model = new TSystemUserModel();
            model.setStatus(GlobalConstant.MODEL_DEL);
            model.setId(id);
            list.add(model);
        }
        boolean flag = systemUserService.updateBatchById(list);
        return flag ? JsonResult.sendOk("删除成功", null) : JsonResult.sendError("删除失败", null);
    }

    /**
     * 冻结账户或者解冻账户
     * 
     * @Title freezeUser
     * @author 于国帅
     * @date 2018年12月31日 下午8:59:00
     * @param id
     * @param state
     * @return Object
     */
    @OperationLog(logName = "冻结或者解冻用户", operationLogType = OperationLogType.OTHER)
    @RequestMapping("freezeUserBatch")
    @ResponseBody
    public Object freezeUserBatch(String ids, Integer state) {
        Long[] idsArray = ConvertUtil.StringToLongArray(ids);
        List<TSystemUserModel> list = new ArrayList<>();
        TSystemUserModel model = null;
        for (Long id : idsArray) {
            model = new TSystemUserModel();
            model.setStatus(state);
            model.setId(id);
            list.add(model);
        }
        String msg = (state == 2) ? "冻结" : "解除冻结";
        boolean flag = systemUserService.updateBatchById(list);
        return flag ? JsonResult.sendOk(msg + "成功", null) : JsonResult.sendError(msg + "失败", null);
    }

    /**
     * 冻结账户或者解冻账户
     * 
     * @Title freezeUser
     * @author 于国帅
     * @date 2018年12月31日 下午8:59:00
     * @param id
     * @param state
     * @return Object
     */
    @OperationLog(logName = "冻结或者解冻用户", operationLogType = OperationLogType.OTHER)
    @RequestMapping("freezeUser")
    @ResponseBody
    public Object freezeUser(Long id, Integer state) {
        TSystemUserModel model = new TSystemUserModel();
        model.setStatus(state);
        model.setId(id);
        boolean flag = systemUserService.updateById(model);
        String msg = (state == 2) ? "冻结" : "解除冻结";
        return flag ? JsonResult.sendOk(msg + "成功", null) : JsonResult.sendError(msg + "失败", null);
    }

    /**
     * 重置密码为默认的6个1
     * 
     * @Title resetPwd
     * @author 于国帅
     * @date 2018年12月31日 下午9:14:12
     * @param id
     * @return Object
     */
    @OperationLog(logName = "重置用户密码", operationLogType = OperationLogType.OTHER)
    @RequestMapping("resetPwd")
    @ResponseBody
    public Object resetPwd(Long id) {
        String defaultPwd = "111111";
        TSystemUserModel model = new TSystemUserModel();
        model.setSalt(RandomStringUtils.random(6, true, true));
        model.setPassword(ShiroKit.md5(defaultPwd, model.getSalt()));
        model.setId(id);
        boolean flag = systemUserService.updateById(model);
        return flag ? JsonResult.sendOk("重置密码成功,密码为" + defaultPwd, null) : JsonResult.sendError("重置密码失败", null);
    }

    /**
     * 跳转个人信息修改
     * 
     * @Title toSystemUserUpdateInfo
     * @author 于国帅
     * @date 2019年2月19日 下午1:34:15
     * @param id
     * @return String
     */
    @RequestMapping("toSystemUserUpdateInfo")
    public String toSystemUserUpdateInfo() {
        Long id = ShiroKit.getUserId();
        TSystemUserModel model = systemUserService.selectById(id);
        request.setAttribute("model", model);
        setRoleList();
        return "system/systemUser/systemUserUpdate"; // 跳转到列表页
    }

    /**
     * 跳转修改密码
     * 
     * @Title toSystemUserUpdatePwd
     * @author 于国帅
     * @date 2019年2月19日 下午1:35:54
     * @return String
     */
    @RequestMapping("toSystemUserUpdatePwd")
    public String toSystemUserUpdatePwd() {
        Long id = ShiroKit.getUserId();
        TSystemUserModel model = systemUserService.selectById(id);
        request.setAttribute("model", model);
        setRoleList();
        return "system/systemUser/updatePwd"; // 跳转到列表页
    }

}
